package com.piedra.httpclient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


/**
 * HttpClientTest.java
 * 
 * ========================
 *It is important to always release the connection regardless of whether the server returned an error or not. 
 *
 * @author linwenbin
 */
public class HttpClientTest {
	public static void main(String[] args) throws Exception{
		//1. Create a instance of the HttpClient.
		HttpClient client = new DefaultHttpClient();
		//Specify a url to access.
		String url = "http://www.baidu.com";
		//2. the method the client access the server.
		HttpGet get = new HttpGet(url);
		//3. get the response that response the content of the from the server 
		HttpResponse response = client.execute(get);
		//4. get the entity.
		HttpEntity entity = response.getEntity();
		if(entity == null){
			//if the entity is null, and you do not do anything because there is no content you can operate.
			return;
		}
		//5. get the inputstream of the entity,so that we can read the content from the server page.
		InputStream in = entity.getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		//6. read something from the server.
		String line = "";
		while((line=reader.readLine()) != null){
			System.out.println(line);
		}
		//7. close all the connection of the server. 
		in.close();
		reader.close();
		client.getConnectionManager().shutdown();
	}
}
